package service

import (
	"singo/model"
	"singo/serializer"
)

// MyPerformanceService 我的绩效管理列表服务
type MyPerformanceService struct {
	Limit     int    `form:"pageSize" json:"pageSize"`
	Start     int    `form:"pageNo" json:"pageNo"`
	StartTime string `form:"start_time" json:"start_time" binding:"required"`
	EndTime   string `form:"end_time" json:"end_time" binding:"required"`
}

// PerformanceListService 全部绩效管理列表服务
type PerformanceListService struct {
	Limit     int    `form:"pageSize" json:"pageSize"`
	Start     int    `form:"pageNo" json:"pageNo"`
	StartTime string `form:"start_time" json:"start_time" binding:"required"`
	EndTime   string `form:"end_time" json:"end_time" binding:"required"`
	ExecuteBy string `form:"execute_by" json:"execute_by"`
}

// MyPerformance 我的绩效管理列表
func (service *MyPerformanceService) MyPerformance(userUID string) serializer.Response {
	tasks := []model.Task{}
	total := 0

	if service.Limit == 0 {
		service.Limit = 10
	}

	if err := model.DB.Model(&tasks).Where("deadline_at BETWEEN ? AND ?", service.StartTime, service.EndTime).Where("execute_by LIKE ?", "%"+userUID+"%").Count(&total).Error; err != nil {
		return serializer.Response{
			Status: 50000,
			Msg:    "数据库连接错误",
			Error:  err.Error(),
		}
	}

	if err := model.DB.Limit(service.Limit).Offset((service.Start-1)*service.Limit).Where("deadline_at BETWEEN ? AND ?", service.StartTime, service.EndTime).Where("execute_by LIKE ?", "%"+userUID+"%").Not("status", 4).Order("review_status, updated_at desc, complete_at desc").Find(&tasks).Error; err != nil {
		return serializer.Response{
			Status: 50000,
			Msg:    "数据库连接错误",
			Error:  err.Error(),
		}
	}

	return serializer.BuildListResponse(serializer.BuildTasksSimple(tasks), uint(total))
}

// PerformanceList 全部绩效管理列表
func (service *PerformanceListService) PerformanceList() serializer.Response {
	tasks := []model.Task{}
	total := 0

	if service.Limit == 0 {
		service.Limit = 10
	}

	if err := model.DB.Model(&tasks).Where("deadline_at BETWEEN ? AND ?", service.StartTime, service.EndTime).Where("execute_by LIKE ?", "%"+service.ExecuteBy+"%").Count(&total).Error; err != nil {
		return serializer.Response{
			Status: 50000,
			Msg:    "数据库连接错误",
			Error:  err.Error(),
		}
	}

	if err := model.DB.Limit(service.Limit).Offset((service.Start-1)*service.Limit).Where("deadline_at BETWEEN ? AND ?", service.StartTime, service.EndTime).Where("execute_by LIKE ?", "%"+service.ExecuteBy+"%").Not("status", 4).Order("review_status, complete_at desc, updated_at desc").Find(&tasks).Error; err != nil {
		return serializer.Response{
			Status: 50000,
			Msg:    "数据库连接错误",
			Error:  err.Error(),
		}
	}

	return serializer.BuildListResponse(serializer.BuildTasks(tasks), uint(total))
}
